import { RouteConfig, ExtendedMenuItem } from '@/types';

export function buildRouteTree(routes: RouteConfig[]) {
  if (!routes || routes.length === 0) return [];
  const dynamicRoutes: RouteConfig[] = [];
  const routeMap = createRouteMap(routes);
  routes.forEach(route => {
    if (route.menuId === null) {
      const currentRoute = routeMap.get(route.menuId);
      if (route.parentId === '0' && currentRoute) {
        dynamicRoutes.push(currentRoute);
      } else {
        if (route.parentId != null && currentRoute) {
          const parentRoute = routeMap.get(route.parentId);
          if (parentRoute) {
            if (!parentRoute.children) {
              parentRoute.children = [];
            }
            parentRoute.children.push(currentRoute);
          }
        }
      }
    }
  });
  return dynamicRoutes;
}

export function generateMenu(routes: RouteConfig[]) {
  // 过滤隐藏的菜单
  const visibleRoutes = routes.filter(route => !route.hidden);
  // 构建路由树
  const routeTree = buildRouteTree(visibleRoutes);
  // 生成菜单列表，同时给每个路由节点追加 fullPath
  return routeTree.map(route => {
    return appendFullPathToRoutes(route, '');
  });
}

// 明确返回类型为 MenuItem
function appendFullPathToRoutes(route: RouteConfig, parentpath: string = ''): ExtendedMenuItem {
  const fullpath = (parentpath + '/' + route.path).replace(/\/+/g, '/');
  // 基础属性（确保包含 children，默认为空数组）
  const baseItem: ExtendedMenuItem = {
    icon: route.icon,
    label: route.menuName || '', // 确保 label 不为 undefined
    key: route.menuId?.toString() || '', // 确保 key 为字符串（antd 要求）
    path: route.path,
    isFrame: route.isFrame,
    fullpath: fullpath,
    children: [], // 始终初始化 children 为空数组
  };

  // 有子路由时递归处理
  if (route.children && route.children.length > 0) {
    baseItem.children = route.children.map(child => appendFullPathToRoutes(child, fullpath));
  }

  return baseItem;
}

// 修改 createRouteMap 函数的返回值类型和空值处理
function createRouteMap(routes: RouteConfig[]) {
  // 始终返回 Map 类型，空数组时返回空 Map
  const routeMap = new Map<string, RouteConfig>();
  if (routes == null || routes.length === 0) return routeMap;

  for (const route of routes) {
    // 推荐使用 for...of 循环更安全
    const currentRoute = {
      ...route,
      element: route.component,
    };
    if (route.menuId != null) {
      routeMap.set(route.menuId, currentRoute);
    }
  }

  return routeMap;
}
